package net.fxug.hokuriku.chocolat.service
{
    import flash.events.Event;
    import flash.events.IOErrorEvent;
    import flash.events.ProgressEvent;
    import flash.events.ServerSocketConnectEvent;
    import flash.net.ServerSocket;
    import flash.net.Socket;
    import flash.text.TextField;
    import flash.utils.describeType;

    import mx.logging.ILogger;
    import mx.logging.Log;
    import mx.logging.targets.TraceTarget;

    import net.fxug.hokuriku.chocolat.events.VoteEvent;

    /**
     * Mock。
     * 伊藤さんのサンプルをコピーしただけのテスト用
     *
     * @author hikaruworld
     */
    public class ServerSocketServerVoteWatcherMock implements IVoteWatcher
    {
        private const PORT:int = 8080;

        private var serverSocket:ServerSocket;
        private var messageField:TextField;

        private var logger:ILogger = Log.getLogger("log");

        public function ServerSocketServerVoteWatcherMock()
        {
            var traceTarget:TraceTarget = new TraceTarget();
            Log.addTarget(traceTarget);
        }


        public function destory():void
        {

        }

        public function isEnabled():Boolean
        {
            return true;
        }

        public function start():void
        {
            serverSocket = new ServerSocket();
            serverSocket.addEventListener(Event.CONNECT, connectHandler);
            serverSocket.addEventListener(Event.CLOSE, closeHandler);

            try
            {
                serverSocket.bind(PORT);
                serverSocket.listen();

                log("listen");

                VoteManager.getInstance().onReady(this);
            }
            catch (e:SecurityError)
            {
                log(e.message);
            }
        }

        private function connectHandler(event:ServerSocketConnectEvent):void
        {
            log("connect");

            var incomingSocket:Socket = event.socket;
            incomingSocket.addEventListener(ProgressEvent.SOCKET_DATA, incomingSocketSocketDataHandler);
            incomingSocket.addEventListener(Event.CLOSE, incomingSocketCloseHandler);
            incomingSocket.addEventListener(IOErrorEvent.IO_ERROR, incomingSocketIOErrorHandler);
        }

        private function closeHandler(event:ServerSocketConnectEvent):void
        {
            serverSocket.close();
            log("close");
        }

        private function incomingSocketSocketDataHandler(event:ProgressEvent):void
        {
            var socket:Socket = event.target as Socket;
            var message:String = socket.readUTFBytes(socket.bytesAvailable);
            log("message:" + message);

            describeType(VoteManager.getInstance());

            if (message.indexOf("hee") > -1)
            {
                var ve:VoteEvent = new VoteEvent(VoteEvent.GOOD_EVENT, [message]);
                VoteManager.getInstance().dispatchVote(ve);
            }
            if (message.indexOf("boo") > -1)
            {
                var bo:VoteEvent = new VoteEvent(VoteEvent.BAD_EVENT, [message]);
                VoteManager.getInstance().dispatchVote(bo);
            }

            socket.writeUTFBytes(message);
            socket.flush();
        }

        private function incomingSocketCloseHandler(event:Event):void
        {
            log("Connection to client closed.");
        }

        private function incomingSocketIOErrorHandler(errorEvent:IOErrorEvent):void
        {
            log("IOError: " + errorEvent.text);
        }

        private function log(str:String):void
        {
            logger.debug(str);
        }

    }
}